<?php

namespace  addons\kuerp\controller;

use addons\kuerp\model\Customers;
use addons\kuerp\model\ExpenseInfo;
use app\admin\model\kuerp\Prefix;
use addons\kuerp\model\ExamineRecord;
use addons\kuerp\model\Message;
use addons\kuerp\model\Flows;
use addons\kuerp\model\StaffMember;
use app\admin\model\department\Admin as AdminDepartment;
use addons\kuerp\model\GoodsSales;
use app\admin\model\Admin;
use think\Db;
use think\Log;
use Exception;
use think\exception\PDOException;
/**
 * 积分申请管理
 *
 * @icon fa fa-circle-o
 */
class ScoreApply extends StaffApi
{

    /**
     * ScoreApply模型对象
     * @var \app\admin\model\kuerp\ScoreApply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \addons\kuerp\model\ScoreApply;
        
    }

    /**
     * 查看
     */
    public function getList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        $adminids = $this->auth->adminids;
        if (!empty($config_examine_admins[$this->auth->id])) {
            $adminids = array_merge($adminids, explode(',', $config_examine_admins[$this->auth->id]));
        }
        $where = [
            'admin_id' => ['in', $adminids],
            'id' => ['exp', Db::raw(' > 0 and ((check_status = 0 and admin_id = '.$this->auth->id.') or check_status > 0)')]
        ];
        
        $order  = 'id desc';
		if (isset($params['name']) && $params['name']) {//
			$where['apply_code'] = ['like', "%{$params['name']}%"];
		}
        //发起人 查询
        $staff_id = input('staff_id', '', 'intval');

        $check_status = input('check_status');//1审核中、2审核通过、3审核未通过
        $purchase_id = input('purchase_id');//订单id
        $ids=input('ids');
        $type = input('type', 1);
        $whereFlow = $followWhere = [];
        // $where = [];
        $times = input('times', '');


        if ($check_status) {
            //0待审核、1审核中、2审核通过、3审核未通过、4撤销
            if ($check_status == 1) {
                $where['check_status'] = ['in', [0, 1]];
                // $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_history_uids)')];
            } elseif ($check_status == 2) {
                $where['check_status'] = 2;
                // $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_history_uids)')];
            } elseif ($check_status == 3) {
                $where['check_status'] = 3;
                // $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_history_uids)')];
            }elseif ($check_status == 4) {
                $where['check_status'] = 4;
                // $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_history_uids)')];
            }elseif ($check_status == 9) {
                $where['check_status'] = 9;
                // $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_history_uids)')];
            }
        }
        if ($type == 1) {//我发起的
            $where['admin_id'] = $this->auth->id;
        } elseif ($type == 2) {//我审批的
            $whereFlow = [['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_history_uids)')]];
        }elseif ($type == 3 && empty($ids)){
            $this->success('请求成功',[]);
        }
        if ($ids) {
            $where['id'] = ['in',explode(',',$ids)];
        }
        // if ($customer_id) {
        //     $where['customer_id'] = $customer_id;
        //     if(isset($where['staff_id']))unset($where['staff_id']);
        // }
        if ($staff_id) {
            $adminid = StaffMember::where('id', $staff_id)->value('admin_id');
            $where['admin_id'] = $adminid;
        }
        if ($purchase_id) {
            $where['goodssales_id'] = $purchase_id;
        }
        if ($times) {
            $times = setTimes($times, 'time');
            $where['createtime'] = ['between', $times];
        }
        $list = $this->model->where($where)->where($whereFlow)->order($order)->paginate($limit);
        foreach ($list as $row) {
            $row->visible(['id','apply_code','total_score', 'add_score','apply_data','admin_id','pay_status','remark','createtime','check_status', 'admin', 'check_last_uid', 'last_checkadmin', 'goodssales_code']);
            
        }
        if ($list->items()) {
            $admins = array_column($list->items(), 'admin_id');
            $check_last_uids = array_column($list->items(), 'check_last_uid');
            $adminids = array_values(array_unique(array_merge($admins, $check_last_uids)));
            $adminlist = Db::name('admin')->where('id', 'in', $adminids)->column('nickname,avatar', 'id');
            foreach ($list as $key => $value) {
                $list[$key]['admin'] = $adminlist[$value['admin_id']] ?? [];
                $list[$key]['last_checkadmin'] = $adminlist[$value['check_last_uid']] ?? [];
                $list[$key]['apply_data'] =$value['apply_data'] ? json_decode($value['apply_data'], true) : [];
                $list[$key]['createtime'] = date('Y-m-d H:i', $value['createtime']);
                if ($type == 2) {
                    //获取最后一条审核日志
                    $last_status = Db::name('examine_log')->where(['relation_type' => 'score', 'relation_id' => $value['id'], 'admin_id' => $this->auth->id])->order('id desc')->value('examine_status');
                    $list[$key]['check_status'] = $last_status == 0 ? 3 : 2;
                }
            }
        }
        // $staticsinfo = $this->model->where($where)->field('sum(cost) as total_cost, sum(if(check_status = 2, cost, 0)) as pass_cost, sum(if(check_status = 1, cost, 0)) as passing_cost, sum(if(check_status = 3, cost, 0)) as nopass_cost,sum(if(check_status = 2 and pay_status = 0, cost, 0)) as nopay_cost,sum(if(pay_status = 1, cost, 0)) as pay_cost')->find()->toArray();//->sum('cost');
        // $result = array("total" => $list->total(), "data" => $list->items());
        $this->success('请求成功', $list);
    }

    //添加费用
    public function apply()
    {
        $params = $this->request->post();
        $goodsSales = new GoodsSales();
        $row = $goodsSales->get($params['purchase_id']);
        if (!$row) {
            $this->error('订单信息不存在');
        }
        if($row['real_money'] > $row['pay_money']){
            $this->error('全都回款后方可申请赠送积分');
        }
        $params['goodssales_id'] = $params['purchase_id'];
        $params['goodssales_code'] = $row['purchase_code'];
        Db::startTrans();
        try {
            $lastId = $this->model->addScoreApply($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            Log::error('申请积分报错：'.$e->getMessage());
            $this->error($e->getMessage());
        }
        $this->success('申请成功',['id'=>$lastId]);
        
    }

    //编辑费用
    public function edit()
    {
        $params = $this->request->post();
        $row = $this->model->get($params['id']);
        if (!$row) {
            $this->error(__('参数错误'));
        }
        if($row['check_status']==1){
            $this->error('不能编辑审核中的数据');
        }
        if($row['check_status']==2){
            $this->error('不能编辑已审核的数据');
        }
        if($row['pay_status']==1){
            $this->error('不能编辑已赠送的数据');
        }
        // 表单验证
        // if (($result = $this->qingdongwmsValidate($params, get_class(),'create')) !== true) {
        //     $this->error($result);
        // }
        Db::startTrans();
        try {
            $result = $this->model->editScoreApply($params, $row);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            Log::error('编辑申请报错：'.$e->getMessage());
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('编辑成功');
        }
    }

    //获取待审批费用数量
    public function getApplyNumber()
    {

        $faqi = $this->model->where([
            'admin_id' => $this->auth->id,
            'check_status' => ['in', [0, 1]]
        ])->count();
        $shenpi = $this->model->where([['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_history_uids)')]])->count();

        $this->success('请求成功', ['faqi' => $faqi, 'shenpi' => $shenpi]);
    }



    //获取费用详情
    public function getDetail()
    {
        $id = input('id', '', 'intval');
        $row = $this->model->get($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }
        $row['admin'] = Admin::where('id', $row['admin_id'])->field('nickname,avatar')->find();
        if($row['admin_id'] == $this->auth->id && $row['check_status'] != 2){
            $row['is_edit'] = 1;
        }else{
            $row['is_edit'] = 0;
        }
        $row['is_operation']=0;
        if($row['admin_id'] == $this->auth->id){
            //是否可以操作
            $row['is_operation']=1;
        }

        $row['is_examine'] = 0;
        if (in_array($this->auth->id, explode(',', $row['check_history_uids']))) {
            $row['check_status'] = 2;
        }
        if ($row['check_status'] == 1) {
            //判断当前人是否有审核权限
            //获取审批流程
            $flows = Flows::where(['relation_type' => Flows::SCORE_STATUS, 'status' => 1])->find();
            $examine_index = 0;
            $cur_flows_item = [];
            $last_examine_indexs = [];
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $cur_flows_item = $value;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
            }
            //系统设置特定审核人员
            $config_examine_admins = config('site.examine_admins');
            $adminids = $this->auth->adminids;
            if (!empty($config_examine_admins[$this->auth->id])) {
                $adminids = array_merge($adminids, explode(',', $config_examine_admins[$this->auth->id]));
            }
            // var_dump($adminids, $row['admin_id']);
            //当前用户在审核流程中 且 当前用户是销售员的上级
            if ($examine_index > 0 && in_array($row['admin_id'], $adminids)) {
                //未到当前用户的审批层级或者已到当前用户的审批层级且当前用户没有还审批
                if ($examine_index > $row['check_step_sort'] || ($examine_index == $row['check_step_sort'] && $cur_flows_item['stafftype'] == 2 && !in_array($this->auth->id, explode(',', $row['check_uids'])))) {
                    //在当前人审核范围内
                    if (in_array($row['check_step_sort'],$last_examine_indexs)) {
                        if ($row['check_step_sort'] == 0) {
                            $parentids = array_unique((new AdminDepartment())->getParentAdminIds($row['admin_id'], true, true));
                            //系统设置特定审核人员
                            if (!empty($config_examine_admins)) {
                                $config_parents = [];
                                foreach ($config_examine_admins as $k => $v) {
                                    if (in_array($row['admin_id'], explode(',', $v))) {
                                        $config_parents[] = $k;
                                    }
                                }
                                $parentids = array_unique(array_merge($parentids, $config_parents));
                            }
                            // var_dump($this->auth->id, $parentids, in_array($this->auth->id, $parentids));
                            //判断当前人是否直属上级，且是否在审核流程中
                            if (in_array($this->auth->id, $parentids)) {
                                $row['is_examine'] = 1;
                            }
                        } else {
                            $row['is_examine'] = 1;
                        }
                    }
                }

                //未到当前用户的审批层级或者已到当前用户的审批层级且当前用户没有还审批
                // if ($examine_index == ($row['check_step_sort']+1) || ($examine_index == $row['check_step_sort'] && $cur_flows_item['stafftype'] == 2 && !in_array($this->auth->id, explode(',', $row['check_uids'])))) {
                //     $row['is_examine'] = 1;
                // }
            }
            // $row['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::EXPENSE_TYPE, $id);
        }
        //获取订单客户
        $customer_id = GoodsSales::where('id', $row['goodssales_id'])->value('customers_id');
        $row['customer'] = Customers::where('id',$customer_id)->field('id,customer_name')->find();
        $row['createtime_text'] = date('Y-m-d H:i:s',$row['createtime']);
        $row['apply_data'] = json_decode($row['apply_data'], true);
        //标记通知已读
        Message::setRead(Message::SCORE_TYPE, $id, $this->auth->id);

        $this->success('请求成功', $row);
    }

    //撤销费用
    public function cancelConsume()
    {
        $id = input('id');
        if(empty($id)){
            $this->error('id不能为空');
        }
        $row=ConsumeModel::where(['id'=>$id])->find();
        if(empty($row)){
            $this->error('信息不存在');
        }
        if($row['staff_id'] != $this->auth->id){
            $this->error('只有创建人可以撤销费用');
        }
        Db::startTrans();
        try {
            ConsumeModel::where(['id'=>$id])->update(['check_status'=>4]);
            ExamineRecord::cancelExaminse( ExamineRecord::CONSUME_TYPE,$id);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('撤销成功');
    }
    


    //获取费用编号
    public function getNumber()
    {
        $code = (new Prefix())->getCodes('',28);
        $this->success('请求成功', ['number' => $code]);
    }


    public function changePayStatus($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $res =$this->model->where(['id'=>$ids])->update(['pay_status'=>1,'pay_time' => time(), 'pay_admin_id' => $this->auth->id,'updatetime'=>time()]);
        if($res){
            $this->success();
        }else{
            $this->error('打款失败');
        }
    }

    /**
     * 撤回申请
     */
    public function backApply($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $res = $this->model->where(['id'=>$ids])->update(['check_status'=>4,'check_step_sort'=>0,'check_uids'=>0,'check_time'=>0,'check_remark'=>'','updatetime'=>time()]);
        if($res){
            $this->success();
        }else{
            $this->error('撤回失败');
        }
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        if (empty($list)) {
            $this->error(__('No rows were found'));
        }
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}

